package com.keyue.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.keyue.common.constant.Constant;
import com.keyue.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


@Slf4j
@Component
public class AdminMetaObjectHandler implements MetaObjectHandler {


    private static final String CREATE_TIME = "createTime";
    private static final String MODIFY_TIME = "modifyTime";
    private static final String CREATE_BY = "createBy";
    private static final String MODIFY_BY = "modifyBy";
    private static final String ENABLE_FLAG = "enableFlag";
    private static final String STRING_CLASS_NAME = "java.lang.String";
    private static final String LONG_CLASS_NAME = "java.lang.Long";

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        this.strictInsertFill(metaObject, CREATE_TIME, LocalDateTime.class, now);
        this.strictInsertFill(metaObject, MODIFY_TIME, LocalDateTime.class, now);
        this.strictInsertFill(metaObject, ENABLE_FLAG, Integer.class, Constant.ENABLE_TEN);
        try {
            UserDetails loginUser = SecurityUtils.getUserDetails();

            this.strictInsertFill(metaObject, CREATE_BY, String.class, loginUser.getUsername());

            this.strictInsertFill(metaObject, MODIFY_BY, String.class, loginUser.getUsername());
        }catch (Exception e) {
            this.strictInsertFill(metaObject, CREATE_BY, String.class, "system");

            this.strictInsertFill(metaObject, MODIFY_BY, String.class, "system");
        }


    }

    @Override
    public void updateFill(MetaObject metaObject) {

        this.strictUpdateFill(metaObject, MODIFY_TIME, LocalDateTime.class, LocalDateTime.now());


        try {
            UserDetails loginUser = SecurityUtils.getUserDetails();
            if (null == loginUser) {
                return;
            }
            this.strictUpdateFill(metaObject, MODIFY_BY, String.class, loginUser.getUsername());
        }catch (Exception e) {
            this.strictUpdateFill(metaObject, MODIFY_BY, String.class, "system");
        }

    }
}
